package com.platform.qujia.controller;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.zxing.WriterException;
import com.platform.qujia.dao.PayWayMapper;
import com.platform.qujia.constantEnum.integralTypeEnum;
import com.platform.qujia.param.request.AddPayOrderParam;
import com.platform.qujia.param.request.LoginBody;
import com.platform.qujia.param.request.PayOrderRequest;
import com.platform.qujia.param.request.updateIntegralRequest;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.CouponPaymetDto;
import com.platform.qujia.pojo.dto.carWashPaymentDto;
import com.platform.qujia.pojo.dto.newCarWashPaymetDto;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import org.apache.axis.encoding.Base64;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <Title> PosMachineController </Title>
 * <Description> POS机端模块功能 </Description>
 * @Date 2021年3月17日
 */

@Controller
//@QuJiaRequest()
@CrossOrigin
@Api(tags = "POS端接口")
public class PosMachineController {
    private static Logger logger = (Logger) LoggerFactory.getLogger(PosMachineController.class);
    @Resource
    private PosMachineService posMachineService;

    @Resource
    private PayOrderService payOrderService;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private AppUserInfoService appUserInfoService;

    @Resource
    private CustomerPointsRecordService customerPointsRecordService;

    @Resource
    private GradeService gradeService;

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Value("${3des.pwd}")
    private String pwd;

    @Resource
    private CouponService couponService;
    @Autowired
    private IPaymentService paymentService;

    @Autowired
    private OrderPayTypeService orderPayTypeService;


    /*
     * POS 根据会员码或者手机号 查询会员信息
     * @param stationId
     * @param memberCode
     * @param mobilePhone
     * @return
     */
    @RequestMapping(value = "/selectMemberToPos", method = RequestMethod.GET)
    @ApiOperation(value = "POS 根据会员码或者手机号 查询会员信息", httpMethod = "GET", notes = "POS 根据会员码或者手机号 查询会员信息")
    @ResponseBody
    public String selectMemberToPos(@RequestParam Integer stationId, String keywords) {
        logger.info("POS 根据会员码或者手机号 查询会员信息 油站id:[{}],关键：[{}]",stationId,keywords);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        //查询油站
        Station station = enterpriseService.selectStationById(stationId);
        if (null != station) {
            if (StringUtils.isNotBlank(keywords)) {
                AppUserInfo appUserInfo = new AppUserInfo();
                appUserInfo.setStationId(station.getEnterpriseId());
                appUserInfo.setKeywords(keywords);
                AppUserInfo appUserInfos = appUserInfoService.getAppUserInfoAndBalance(appUserInfo);
                if (ObjectUtils.isEmpty(appUserInfos)){
                    resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
                    return gson.toJson(resultData);
                }
                Grade grade = new Grade();
                grade.setDeleteFlag("0");
                appUserInfos.setGradeName("暂无");
                grade.setEnterpriseId(Long.valueOf(station.getEnterpriseId()));
                //获取会员等级
                List<Grade> gradeList = gradeService.selectGradeList(grade);
                if (null != gradeList && gradeList.size() > 0) {
                    for (Grade g : gradeList) {
                        if (appUserInfos.getGrowUpValue() >= Integer.valueOf(g.getGradeGrowValue())) {
                            appUserInfos.setGradeName(g.getGradeName());
                            break;
                        }
                    }
                }
                resultData = ResultData.success(appUserInfos);
            }else{
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        } else {
            resultData = ResultData.error(CodeMsg.STATION_NOT_EXIST);
        }
        return gson.toJson(resultData);
    }

    /*
     * POS 扫码核销用户积分
     * @param memberCode
     * @param integral
     * @param stationId
     * @return
     */
    @RequestMapping(value = "/writeOffUserIntegral", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "扫码核销用户积分", httpMethod = "GET", notes = "扫码核销用户积分")
    @Transactional
    public String writeOffUserIntegral(@ApiParam(value = "会员码", required = true) @RequestParam String memberCode,
                                       @ApiParam(value = "积分", required = true) @RequestParam Integer integral,
                                       @ApiParam(value = "核销人员ID（POS机登陆人员）", required = true) @RequestParam Integer userId,
                                       @ApiParam(value = "油站ID", required = true) @RequestParam Integer stationId) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if (StringUtils.isNotBlank(memberCode) && integral != null && stationId != null) {
            //1.查询用户信息
            AppUserInfo appUser = new AppUserInfo();
            appUser.setMemberCode(memberCode);
            AppUserInfo appUserInfo = appUserInfoService.getAppUserInfoByMemberCode(appUser);
            if (appUserInfo != null) {
                Integer integralUser = appUserInfo.getIntegral();
                //2.判断积分是否满足扣除积分，满足扣除；生成积分记录；
                if (integralUser >= integral) {
                    int surplusIntegral = integralUser - integral;
                    appUser.setIntegral(surplusIntegral);
                    appUser.setStationId(appUserInfo.getStationId());
                    //appUser.setUnionId(appUserInfo.getUnionId());
                    appUser.setMobilePhone(appUserInfo.getMobilePhone());
                    appUserInfoService.updateAppUserIntegral(appUser);

                    //3.生成积分记录
                    CustomerPointsRecord customerPointsRecord = new CustomerPointsRecord();
                    customerPointsRecord.setCreateTime(new Date());
                    customerPointsRecord.setCustomerName(appUserInfo.getBlogNickName());
                    customerPointsRecord.setIntegral(integral);
                    customerPointsRecord.setRecordType("-");
                    customerPointsRecord.setUnionId(appUserInfo.getUnionId());
                    customerPointsRecord.setStationId(stationId);
                    customerPointsRecord.setWriteOffUserId(userId);
                    customerPointsRecord.setMobilePhone(appUserInfo.getMobilePhone());
                    customerPointsRecord.setAction(integralTypeEnum.MANUAL_REDUCTION);
                    customerPointsRecordService.insertCustomerPointsRecordInfo(customerPointsRecord);
                    customerPointsRecordService.sendwxgzh(stationId,appUserInfo.getMobilePhone(),integral,surplusIntegral,"-");
                    //客户剩余积分
                    customerPointsRecord.setSurplusIntegral(surplusIntegral);
                    resultData = ResultData.success(customerPointsRecord);
                } else {
                    resultData = ResultData.error(CodeMsg.INTEGRAL_ERROR);
                }
            } else {
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    //POS机端用户登录
    @RequestMapping(value = "/loginPosMachine", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "pos登录", httpMethod = "POST", notes = "pos登录：3des加密密码：LAnZ8RRSkIY0EGVYheu2IjEk；参数信息：userName(用户名); password：密码（加密后的字符串）；deviceNo（设备唯一编码）")
    public String loginPosMachine(@RequestBody LoginBody loginBody) {

        //Using generated security password: a78f4bd0-6087-4fff-ae5d-f2e4cd8c7961
        Gson gson = new Gson();
        //返回结果集
        ResultData resultData = null;
        if (StringUtils.isNotBlank(loginBody.getUserName()) && StringUtils.isNotBlank(loginBody.getPassword()) && StringUtils.isNotBlank(loginBody.getDeviceNo())) {
            SysUser sysUser = posMachineService.selectUserByUserName(loginBody.getUserName());
            if (sysUser != null) {
                if (sysUser.getStatus().equals("0")) {
                    if (StringUtils.isNotBlank(sysUser.getUserLeval()) && "2".equals(sysUser.getUserLeval())) {
                        String deptId = sysUser.getStationId();
                        String password = sysUser.getPassword();
                        //password = CryptUtil.desedeDecrypt(password);
                        String webPassword = loginBody.getPassword();   //前端传来加密码
                        String ps = DESUtils.decrypt(webPassword, pwd);
                        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                        //密码加密判断已加密密码是否与真实密码相同
                        boolean matches = bCryptPasswordEncoder.matches(ps, password);
                        if (matches) {
                            //查询当前站点
                            Station station = enterpriseService.selectStationById(Integer.valueOf(deptId));
                            if (station != null && StringUtils.isNoneBlank(station.getDeleteStatus()) && station.getDeleteStatus().equals("0")) {

                                List<OrderPayType> orderPayTypes = orderPayTypeService.selectOrderPayType(Long.valueOf(station.getStationId()));

                                if (StringUtils.isNoneBlank(station.getStatus()) && station.getStatus().equals("1")) {
                                    StationDeviceManager stationDeviceManager = new StationDeviceManager();
                                    stationDeviceManager.setDeviceNo(loginBody.getDeviceNo());
                                    stationDeviceManager.setStationId(Integer.valueOf(deptId));
                                    //查询传来设备码与登录账户所在油站是否为同一个
                                    StationDeviceManager stationDeviceManagerInfo = posMachineService.getStationDeviceManagerNoCache(stationDeviceManager);


                                    if (stationDeviceManagerInfo != null) {
                                        if(StringUtils.isNotEmpty(stationDeviceManagerInfo.getDeviceNo())){
                                            String key = "PosMachineServiceImpl_getStationDeviceManager::s_"+station.getStationId()+"d_"+stationDeviceManagerInfo.getDeviceNo();
                                            redisCacheUtil.deleteObject(key);
                                        }
                                        if (StringUtils.isNotBlank(sysUser.getGun())||stationDeviceManagerInfo.getBindingType().equals(StationDeviceManager.bindingType_gun)) {
                                            SysUser s = new SysUser();
                                            s.setNickName(sysUser.getNickName());
                                            s.setDeptId(sysUser.getDeptId());
                                            s.setAvatar(sysUser.getAvatar());
                                            s.setUserName(sysUser.getUserName());
                                            s.setPhonenumber(sysUser.getPhonenumber());
                                            s.setSex(sysUser.getSex());
                                            s.setUserId(sysUser.getUserId());
                                            s.setDeptId(sysUser.getDeptId());
                                            s.setStationId(station.getStationId().toString());
                                            s.setEnterpriseId(sysUser.getEnterpriseId());
                                            s.setStationName(station.getStationName());
                                            s.setEmployeeAppletFlag(station.getEmployeeAppletFlag());
                                            s.setOrderPayTypeList(orderPayTypes);
                                            if(stationDeviceManagerInfo.getBindingType().equals(StationDeviceManager.bindingType_staff)){
                                                StaOilGun staOilGun = new StaOilGun();
                                                staOilGun.setStationId(Integer.valueOf(sysUser.getStationId()));
                                                staOilGun.setGunList(sysUser.getGun().split(","));
                                                List<StaOilGun> staOilGunList = enterpriseService.selectStaOilGunList(staOilGun);
                                                if (null != staOilGunList && staOilGunList.size() > 0) {
                                                    resultData = ResultData.success(s);
                                                } else {
                                                    resultData = ResultData.error(CodeMsg.NO_USER_HAVE_GUN);
                                                }

                                            }else{
                                                //绑定油枪只能用油站账号登录
                                                List<SysRole> roles=posMachineService.selectUserRoleByUserId(sysUser.getUserId());
                                                List<String> collect = roles.stream().map(r -> r.getRoleName()).collect(Collectors.toList());
                                                resultData = ResultData.success(s);
                                                if(!collect.contains("油站")){
                                                    resultData = ResultData.error(CodeMsg.NO_STATION_ROLE);
                                                }
                                            }

                                        } else {
                                            resultData = ResultData.error(CodeMsg.NO_USER_HAVE_GUN);
                                        }
                                    } else {
                                        //当前登录账号与油站所绑定POS不一致
                                        resultData = ResultData.error(CodeMsg.ERROR_DEVICE_USER);
                                    }
                                } else {
                                    resultData = ResultData.error(CodeMsg.STATION_STOP_USING);
                                }
                            } else {
                                resultData = ResultData.error(CodeMsg.STATION_NOT_EXIST);
                            }
                        } else {
                            resultData = ResultData.error(CodeMsg.PASSWORD_ERROR);
                        }
                    } else {
                        resultData = ResultData.error(CodeMsg.USERNAME_LEVEL_ERROR);
                    }
                } else if (sysUser.getStatus().equals("1")) {
                    resultData = ResultData.error(CodeMsg.ACCOUNT_DISABLE);
                }
            } else {
                resultData = ResultData.error(CodeMsg.USER_NOT_EXSIST);
            }
        }
        return gson.toJson(resultData);
    }

    private boolean checkUserDeviceOilGun(StationDeviceManager deviceManager, SysUser sysUser) {
        if(StringUtils.isEmpty(deviceManager.getGunNo())){
            //如果设备没有绑定油枪
            return true;
        }
        if(StringUtils.isEmpty(sysUser.getGun())){
            //如果员工没有绑定有枪，设备绑定了油枪
            return false;
        }
        List<String> list = Arrays.asList(deviceManager.getGunNo().split(","));
        List<String> list2 = Arrays.asList(sysUser.getGun().split(","));
        if(Collections.disjoint(list,list2)){
            //不存在交集
            return false;
        }
        return true;
    }


    //根据POS机tusn获取该油站油枪绑定的POS机信息
    @RequestMapping(value = "/getStationDeviceManagerBytusn", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "POS机根据tusn获取该油站油枪绑定的POS机信息", httpMethod = "GET", notes = "获取该油站油枪绑定的POS机信息")
    public String getStationDeviceManagerBytusn(@ApiParam(value = "POS码", required = true) @RequestParam String tusn) {
        Gson gson = new Gson();
        //返回结果集
        ResultData resultData = null;
        if (StringUtils.isNotBlank(tusn)) {
            StationDeviceManager stationDeviceManager = new StationDeviceManager();
            stationDeviceManager.setDeviceNo(tusn);
            //获取油枪绑定的打印设备信息
            StationDeviceManager stationDeviceManagerList = posMachineService.getStationDeviceManager(stationDeviceManager);
            resultData = ResultData.success(stationDeviceManagerList);
        } else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    //POS机根据随机码查询订单信息
    @RequestMapping(value = "/selectPosPayOrderInfoByOrderRandomId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "POS机根据随机码查询订单信息", httpMethod = "GET", notes = "POS机根据随机码查询订单信息")
    public String selectPosPayOrderInfoByOrderRandomId(@ApiParam(value = "POS码", required = true) @RequestParam String orderRandomId) {

        logger.info("/selectPosPayOrderInfoByOrderRandomId--orderRandomId:" + orderRandomId);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //返回结果集
        ResultData resultData = null;
        if (StringUtils.isNotBlank(orderRandomId)) {
            List<PayOrder> payOrderList = payOrderService.selectPosPayOrderListInfoByOrderRandomId(orderRandomId);
            PayOrder filterPayorder = null;

            // 防止多个orderRandomId，挑选一个支付成功的
            if (payOrderList.size() == 1) {
                filterPayorder = payOrderList.get(0);
            } else if (payOrderList.size() == 0) {
                // filterPayorder = new PayOrder();
                // 不知道之前写的啥玩意 兼容这样写，按上面的写法pos报错
                return gson.toJson(ResultData.error(CodeMsg.PARAMS_NUll));
            } else {
                for (PayOrder payOrder : payOrderList) {
                    if ("1".equals(payOrder.getStatus())) {
                        filterPayorder = payOrder;
                        break;
                    }
                }
                if (filterPayorder == null) {
                    filterPayorder = payOrderList.get(0);
                }
            }
            resultData = ResultData.success(filterPayorder);

        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    // 获取订单的支付方式列表
    @GetMapping(value = "/selectPayTypeList")
    @ResponseBody
    @ApiOperation(value = "获取订单的支付方式列表", httpMethod = "GET")
    public String selectPayTypeList() {
        Gson gson = new Gson();
        //返回结果集
        ResultData resultData = null;
        List<PayType> payTypeList = payOrderService.selectPayTypeList();
        Map<String, Object> map = new HashMap<>();
        map.put("payTypeList", payTypeList);
        resultData = ResultData.success(map);
        return gson.toJson(resultData);
    }

    /*
     * 查询订单列表
     * @param stationId
     * @param userName
     * @return
     */
    @RequestMapping(value = "/selectPosPayOrdersList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单列表", httpMethod = "POST", notes = "查询订单列表所用到参数：stationId(油站ID);pageNum（页码）；pageSize（页面大小）； beginTime（开始时间）；endTime（结束时间）；支付方式（非必传）")
    public String selectPosPayOrdersList(@RequestBody PayOrder request) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

//        // pos查询订单，避免日志里全是这玩意，就不打印了
//        if(redisCacheUtil.hasKey("selectPosPayOrdersListLogFlag") && redisCacheUtil.getCacheObject("selectPosPayOrdersListLogFlag") != null){
//             logger.info("/selectPosPayOrdersList-deviceNo:"  + request.getDeviceNo() + "request:"+ request.toString());
//            // logger.info("POS查询订单参数：deviceNo: " + request.getDeviceNo() + "; orderPerFlag: " + request.getNoOrderPerFlag() + "; userId: " + request.getUserId());
//        }

        //返回结果集
        ResultData resultData = null;
        if (request.getStationId() != null) {
            PayOrder payOrder = new PayOrder();
            payOrder.setStationId(request.getStationId());
            payOrder.setBeginTime(request.getBeginTime());
            payOrder.setEndTime(request.getEndTime());
            payOrder.setPayType(request.getPayType());
            payOrder.setStatus(request.getStatus());
            payOrder.setOilPersonnelId(request.getUserId());
            payOrder.setNoOrderPerFlag(request.getNoOrderPerFlag());
            payOrder.setDeviceNo(request.getDeviceNo());
            Map<String, Object> resultMap = new HashMap<>();
            //分页
            if (request.getPageNum() != null && request.getPageSize() != null) {
                PageHelper.startPage(request.getPageNum(), request.getPageSize());
                if (StringUtils.isNotBlank(request.getDeviceNo())) {
                    // 查一下设备绑定的加油员
                    StationDeviceManager stationDeviceManager = posMachineService.getStationDeviceManager(
                            StationDeviceManager.builder().deviceNo(request.getDeviceNo()).stationId(request.getStationId()).build());
                    if (ObjectUtils.isEmpty(stationDeviceManager) || stationDeviceManager.getUserIds() == null){
                        logger.info("request.getDeviceNo-----" + request.getDeviceNo() +"request.getStationId()---"+request.getStationId());

                    }
                    if(stationDeviceManager!=null&&StringUtils.isNotEmpty(stationDeviceManager.getBindingType())){
                        payOrder.setBindingType(stationDeviceManager.getBindingType());
                        if(stationDeviceManager.getBindingType().equals(StationDeviceManager.bindingType_gun)){
                            payOrder.setOilGun(stationDeviceManager.getGunNo());
                        }else{
                            String userIds = stationDeviceManager.getUserIds();
                            payOrder.setOilPersonnelId(userIds);
                        }
                    }

                }

                List<PayOrder> payOrderList = payOrderService.selectPayOrderListFormater2(payOrder);
                PageInfo pageInfo = new PageInfo(payOrderList);
                resultMap.put("orderList", pageInfo);
                //获取
                PayOrder order = new PayOrder();
                order.setStationId(request.getStationId());
                order.setStatus("1");
                order.setBeginTime(request.getBeginTime());
                order.setEndTime(request.getEndTime());
                //查询要班结订单总和
                order.setGroupBy("");
                order.setOilPersonnelId(request.getUserId());
                List<Map> listSumList = payOrderService.selectSum(order);
//                long currentTimeMillisEnd = System.currentTimeMillis();
//                logger.info("查询订单结束时间毫秒：" + System.currentTimeMillis());
//                logger.info("查询订单所需时间毫秒：" + (currentTimeMillisEnd-currentTimeMillisStart));
                resultMap.put("listSum", listSumList.get(0));
                resultData = ResultData.success(resultMap);
//                logger.info("pos机查询订单selectPosPayOrdersList 请求参数：[{}],返回结果：[{}]", JSONObject.toJSONString(request),payOrderList.size());
            } else {
                resultData = ResultData.error(CodeMsg.PARAMS_NUll);
            }
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    /*
     * 查询小程序现金支付轮询订单列表
     * @param stationId
     * @param userName
     * @return
     */
    @RequestMapping(value = "/posSelectAppCashPayOrdersList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询小程序现金支付轮询订单列表", httpMethod = "POST")
    public String posSelectAppCashPayOrdersList(@RequestBody PayOrder request) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        //logger.info("POS查询订单参数：deviceNo: " + request.getDeviceNo() + "; orderPerFlag: " + request.getNoOrderPerFlag() + "; userId: " + request.getUserId());
        //返回结果集
        ResultData resultData = null;
        if (request.getStationId() != null) {
            String oilPersonnelId = request.getUserId();
            if (StringUtils.isNotBlank(request.getDeviceNo())) {
                StationDeviceManager stationDeviceManager = posMachineService.getStationDeviceManager(
                        StationDeviceManager.builder().deviceNo(request.getDeviceNo()).stationId(request.getStationId()).build());
                oilPersonnelId = stationDeviceManager.getUserIds();
            }
            List<PayOrder> payOrderList = payOrderService.posSelectAppCashPayOrdersList(PayOrder.builder()
                    .xJStatus("0")
                    .status(request.getStatus())
                    .noOrderPerFlag(request.getNoOrderPerFlag())
                    .stationId(request.getStationId())
                    .payType("xj")
                    .oilPersonnelId(oilPersonnelId).build());
            resultData = ResultData.success(payOrderList);
        } else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }


    /**
     * 导入
     */
    @PostMapping("/upPostErrorLog")
    @ResponseBody
    public String importCardExcelFile(@RequestParam("file") MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()){
            return ResultData.errorJson("禁止上传空文件");
        }
        String basePath = System.getProperty("user.dir");;
        String filePath = basePath + "/posErrorLog/" + file.getOriginalFilename();
        File desFile = new File(filePath);
        if (!desFile.getParentFile().exists()) {
            desFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IllegalStateException | IOException e) {
            logger.error("/upPostErrorLog",e);
            return ResultData.errorJson(e.getMessage());
        }

        return ResultData.successJson("上传成功");
    }


    /*
     * oss sts服务器
     * @param payInfoRequest
     * @return
     */
    @ApiOperation(value = "消费支付拉起第三方支付", httpMethod = "POST", notes = "消费支付拉起第三方支付")
    @PostMapping(value = "/getOssToken")
    public String getOssToken(){
        try{
            String OSSTOKENKEY = "oss_token";

            if(redisCacheUtil.hasKey(OSSTOKENKEY) && redisCacheUtil.getCacheMap(OSSTOKENKEY) != null) {
                return ResultData.successJson(redisCacheUtil.getCacheMap(OSSTOKENKEY));
            }
            //构建一个阿里云客户端，用于发起请求。
            //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
            String regionId = "cn-qingdao";
            String accessKeyId = "LTAI5tBLxJT5TJ1baDkjULig";
            String secret = "n3Ul0tUSf8NM2Ch6GkndPUiUpr5Xja";
            DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
            IAcsClient client = new DefaultAcsClient(profile);



            //构造请求，设置参数。关于参数含义和设置方法，请参见《API参考》。
            AssumeRoleRequest request = new AssumeRoleRequest();
            String ARN = "acs:ram::1368322258748344:role/ramosstest";
            //request.setRegionId(regionId);
            request.setRoleArn(ARN);
            request.setRoleSessionName("RamOssTest");

            AssumeRoleResponse response = client.getAcsResponse(request);
            logger.info("/getOssToken-阿里oss返回值:" + new Gson().toJson(response));



            HashMap<String, Object> resultMap = new HashMap<>();
            resultMap.put("expiration", response.getCredentials().getExpiration());
            resultMap.put("accessKeyId", response.getCredentials().getAccessKeyId());
            resultMap.put("accessKeySecret", response.getCredentials().getAccessKeySecret());
            resultMap.put("securityToken", response.getCredentials().getSecurityToken());
            resultMap.put("RequestId", response.getRequestId());


            redisCacheUtil.setCacheMap(OSSTOKENKEY, resultMap);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            long eTime = df.parse((String)resultMap.get("expiration")).getTime() + 8 * 60 * 60L * 1000;
            long nTime = new Date().getTime();
            long expirationTime = (eTime - nTime) / 1000 - 2L ;
            redisCacheUtil.expire(OSSTOKENKEY, 1, TimeUnit.SECONDS);

            return ResultData.successJson(resultMap);

        } catch (Exception e) {
            logger.error("/getOssToken-", e);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultData.errorJson(e.getMessage());
        }

    }
    @RequestMapping(value = "/updateIntegral", method = RequestMethod.POST)
    @ApiOperation(value = "积分调整", httpMethod = "POST", notes = "POS机给会员积分调整")
    @ResponseBody
    public String updateIntegral(@Valid @RequestBody updateIntegralRequest integralRequest) throws Exception {
        //根据油站id获取油站信息
        logger.info("updateIntegral-积分调整入参：{}",integralRequest);
        if (integralRequest.getPoints().length() > 10){
           return ResultData.errorJson("积分长度超长，不能超过10位数字");
        }
        Station station = enterpriseService.selectStationById(integralRequest.getStationId());
        logger.info("获取油站信息：{}",station);
        if (null != station){
            AppUserInfo appUserInfo = new AppUserInfo();
            //获取油企id
            appUserInfo.setStationId(station.getEnterpriseId());
            appUserInfo.setKeywords(integralRequest.getKeywords());
            //获取用户信息
            AppUserInfo userInfo = appUserInfoService.getAppUserInfoAndBalance(appUserInfo);
            logger.info("获取用户信息：{}",userInfo);
            if (ObjectUtils.isNotEmpty(userInfo)){
                //用户积分
                Integer oidPoints = userInfo.getIntegral();
                //如果用户积分等于O 不可再扣减
                if ( integralRequest.getType() == 0 && oidPoints - Integer.valueOf(integralRequest.getPoints()) < 0 ){
                    return ResultData.errorJson("该用户剩余积分不够扣减");
                }
                //更新用户积分
                logger.info("更新用户积分————入参：类型：{},传入的积分：{},油站信息：{},用户信息：{},旧积分：{}",integralRequest.getType(), integralRequest.getPoints(), station, userInfo, oidPoints);
                CustomerPointsRecord customerPointsRecord = customerPointsRecordService.updateIntegral(integralRequest.getType(), Integer.valueOf(integralRequest.getPoints()), station, userInfo, oidPoints);
                logger.info("updateIntegral--出参：{}",customerPointsRecord);
                if (ObjectUtils.isEmpty(customerPointsRecord)){
                    return ResultData.errorJson("用户积分更新失败");
                }

                return ResultData.successJson(customerPointsRecord);
            }
        }
        return ResultData.errorJson(CodeMsg.STATION_NOT_EXIST.getMessage());
    }

    @SneakyThrows
    @RequestMapping(value = "/carWashPayment", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "洗车券核销", httpMethod = "POST", notes = "pos机扫码核销洗车券")
    public  ResultData<?> carWashPayment(@Valid @RequestBody carWashPaymentDto cw){
        logger.info("carWashPayment--接口参数:{}",cw);
        return couponService.carWashCouponDestroy(cw);
    }

    @ApiOperation(value = "查询油站支付渠道",notes = "data.channel 支付渠道号，1-随行付，5-云化，默认找后台配置的，找不到找随行付的，都没有会报错")
    @GetMapping("getStationPayWay")
    @ResponseBody
    public ResultData<Map<String,String>> getStationPayWay(@RequestParam Integer stationId){
        PayWay payWay = paymentService.getStationPosPayWay(stationId);
        if (payWay==null) {
            throw new CustomException("找不到支付渠道");
        }
        return ResultData.success(Collections.singletonMap("channel",payWay.getPayType()));
    }

    @RequestMapping(value = "/newCarWashPayment", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "核销", httpMethod = "POST", notes = "pos机扫码核销")
    public  ResultData<?> newCarWashPayment(@Valid @RequestBody newCarWashPaymetDto cw){
        logger.info("newCarWashPayment--接口参数:{}",cw);
        return couponService.newCarWashCouponDestroy(cw);
    }

    @RequestMapping(value = "/couponDestroy", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "核销", httpMethod = "POST", notes = "pos机扫码核销")
    public  ResultData<?> couponDestroy(@Valid @RequestBody CouponPaymetDto cw){
        logger.info("couponDestroy--接口参数:{}",cw);
        return couponService.couponDestroy(cw);
    }


    @RequestMapping(value = "/control/selectPosPayOrdersList", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "pos机查询订单", httpMethod = "POST")
    public ResultData selectControlPosPayOrders(@RequestBody PayOrder request) {
        if (Objects.isNull(request) || Objects.isNull(request.getStationId())) {
            return ResultData.error(CodeMsg.PARAMS_NUll);
        }

        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(request.getStationId());
        payOrder.setBeginTime(request.getBeginTime());
        payOrder.setEndTime(request.getEndTime());
        payOrder.setPayType(request.getPayType());
        payOrder.setStatus(request.getStatus());
        payOrder.setOilPersonnelId(request.getUserId());
        payOrder.setNoOrderPerFlag(request.getNoOrderPerFlag());
        payOrder.setDeviceNo(request.getDeviceNo());

        String beforeFiveMinutes = DateUtils.beforeThirtyMinutes(5);
        if(Objects.isNull(request.getBeginTime())){
            payOrder.setBeginTime(beforeFiveMinutes);
        }

        if(Objects.nonNull(request.getBeginTime()) && (beforeFiveMinutes.compareTo(request.getBeginTime()) > 0)){
            payOrder.setBeginTime(beforeFiveMinutes);
        }

        Map<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNotBlank(request.getDeviceNo())) {
            // 查一下设备绑定的加油员
            StationDeviceManager stationDeviceManager = posMachineService.getStationDeviceManager(
                    StationDeviceManager.builder().deviceNo(request.getDeviceNo()).stationId(request.getStationId()).build());
            if (ObjectUtils.isEmpty(stationDeviceManager) || stationDeviceManager.getUserIds() == null) {
                logger.info("request.getDeviceNo-----" + request.getDeviceNo() + "request.getStationId()---" + request.getStationId());

            }
            if (stationDeviceManager != null && StringUtils.isNotEmpty(stationDeviceManager.getBindingType())) {
                payOrder.setBindingType(stationDeviceManager.getBindingType());
                if (stationDeviceManager.getBindingType().equals(StationDeviceManager.bindingType_gun)) {
                    payOrder.setOilGun(stationDeviceManager.getGunNo());
                } else {
                    String userIds = stationDeviceManager.getUserIds();
                    payOrder.setOilPersonnelId(userIds);
                }
            }

        }

        List<PayOrder> payOrderList = payOrderService.selectPayOrderListFormater3(payOrder);
        PageInfo pageInfo = new PageInfo(payOrderList);
        resultMap.put("orderList", pageInfo);
        //获取
        PayOrder order = new PayOrder();
        order.setStationId(request.getStationId());
        order.setStatus("1");
        order.setBeginTime(request.getBeginTime());
        order.setEndTime(request.getEndTime());
        //查询要班结订单总和
        order.setGroupBy("");
        order.setOilPersonnelId(request.getUserId());
        List<Map> listSumList = payOrderService.selectSum(order);

        resultMap.put("listSum", listSumList.get(0));
        resultMap.put("nowTime",DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD_HH_MM_SS));
        return ResultData.success(resultMap);
    }

}
